import 'dart:convert';
import 'package:dio/dio.dart' as dio;
import 'package:flutter/cupertino.dart';
import 'package:flutter_quill/flutter_quill.dart';
import 'package:flutter_quill/quill_delta.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
import 'package:smart_translator/app/db/DbDAOHelper.dart';
import 'package:smart_translator/app/utils/CommonUtil.dart';
import 'package:sse_stream/sse_stream.dart';
import '../../db/database.dart';
import '../../modules/recordscriptDetail/controllers/recordscript_detail_controller.dart';
import '../../utils/tips.dart';
import 'RecordTranscriptViewRecordingController.dart';
import 'package:smart_translator/app/services/AudioService.dart' as audio;

class RecordTransciptSummeryController extends GetxController {


  var summaryContent = ''.obs;
  String sessionId = '';

  RecordTransciptSummeryController(this.sessionId);


  QuillController quillController = QuillController.basic();

  var editorModition = false.obs;

  ScrollController singleChildController = ScrollController();

  var enableSelectionToolbar = true.obs;

  final FocusNode focusNode = FocusNode();

  @override
  void onInit() {
    super.onInit();

    quillController.addListener((){
      saveModification();
    });

    focusNode.addListener(() {

      if (focusNode.hasFocus) {
        print("TextField 获得焦点");
      } else {
        print("TextField 失去焦点");
        saveModification();
      }
    });

    loadData();
  }


  // 滚动到底部的方法
  void scrollToBottom() {
    // 确保控制器已挂载且滚动视图有内容
    if (singleChildController.hasClients) {
      // 直接跳转到最底部（无动画）
      singleChildController.jumpTo(singleChildController.position.maxScrollExtent);
    }
  }



  loadData() {
     DbDAOHelper().getSummaryBySessionId(sessionId).then((item) {
        if (item != null) {
          summaryContent.value = utf8.decode(item.s_content);
          if (!summaryContent.startsWith('[{')) { // 非 json串.
            quillController.document = Document.fromDelta(
              // 使用 Delta 格式初始化文本
              Delta()..insert('${summaryContent.value} \n'),
            );

          } else {
            quillController.document = Document.fromJson(json.decode(summaryContent.value));
          }

          quillController.readOnly = true;

        }
     });
  }

  @override
  void onReady() {
    super.onReady();

  }

  void generateSummery () async {
    audio.AudioService audioService = Get.find<audio.AudioService>();
    if (audioService.isPlaying.value) {
        Tips.showToast('正在转写中,暂无法生成总结.');
        return;
    }

    // Tips.showLoading();
    summaryContent.value = '';
    Tips.showToast('生成中,请稍后...');
    DbDAOHelper().obtainTranscriptsBySessionId(int.parse(sessionId)).then((scriptList) async {
        String summerizeText = '';
        scriptList.forEach((audioscript) {
          summerizeText = summerizeText + audioscript.a_text;

        });

        if (summerizeText.trim() == '') { //从内存中获取到总结内容.
           // 获取内存中的数据.
          RecordTranscriptViewRecordingController recordTranscriptViewRecordingController = Get.find<RecordTranscriptViewRecordingController>();
          recordTranscriptViewRecordingController.audioTranscriptSource.forEach((item) {
            summerizeText = summerizeText + item.a_text;
          });

          summerizeText = summerizeText + recordTranscriptViewRecordingController.finalFromLanguage.value;

        }

        if (summerizeText.trim() == '') {
          Tips.showToast('没有找到总结内容.');
          return;
        }

        print('总结内容::: ${summerizeText}');

        dio.Response resp = await dio.Dio(
        ).post(
          'https://xy-apis.newtranx.com/chat/v1/summary?stream=true',
          data: json.encode({
            'content': summerizeText
          }),
          options: dio.Options(
            responseType: dio.ResponseType.stream,
            headers: {
              'X-Api-Key': '264e03da4958e5ea405dd8f63b87da898757b821',
              'Content-Type': 'application/json'},
          ),

        );

        resp.data?.stream
            .cast<List<int>>()
            .transform(Utf8Decoder())
            .transform(const SseEventTransformer())
            .listen((event) {
                 Map<String,dynamic> contentParams = json.decode(event.data!);
                 String content = contentParams['data']['Delta']['Content'];
                 summaryContent.value = summaryContent.value + content;

             },
             onDone: () {
                // 流正常结束时触发
                Tips.showToast('总结生成完成');
                print('Stream 已正常结束');

                // 生成json传, 获取到session的名称,如果是纯字符串就替换掉.
                String summeryJson = summaryContent.value;
                Map<String,dynamic> data = json.decode(summeryJson);

                DbDAOHelper().saveSummary(int.parse(sessionId), data['content'].toString());

                quillController.document = Document.fromDelta(
                  // 使用 Delta 格式初始化文本
                  Delta()..insert('${data['content'].toString()} \n'),
                );
                quillController.readOnly = true;


                RecordscriptDetailController recordscriptDetailController = Get.find<RecordscriptDetailController>();
                if (recordscriptDetailController != null) {
                  Session session = recordscriptDetailController.session.value;
                  String sessionName = session.session_name;
                  if(CommonUtil.isNumeric(sessionName)) {
                     DbDAOHelper().updateSessionNameBySessionId(session.id, data['title'].toString());
                     recordscriptDetailController.loadData();
                  }
                }


             },
        );

    });

  }

  @override
  void onClose() {
    super.onClose();
    focusNode.dispose();
  }


  void changeModification() {
    editorModition.value = true;
    quillController.readOnly = false;
    enableSelectionToolbar.value = false;
    Future.delayed(Duration(milliseconds: 500),() {
      scrollToBottom();
    });

  }

  /*void cancelModification() {
    editorModition.value = false;
    quillController.readOnly = true;

    enableSelectionToolbar.value = true;
  }*/

  void saveModification() async {
    if (!editorModition.value) return;

    final deltaJson = quillController.document.toDelta().toJson();
    // update summery.
    await DbDAOHelper().saveSummary(int.parse(sessionId), json.encode(deltaJson));
    /*editorModition.value = false;
    quillController.readOnly = true;
    enableSelectionToolbar.value = true;
    loadData();*/

  }



 /* // 保存到 SharedPreferences
  final prefs = await SharedPreferences.getInstance();
  final deltaJson = _controller.document.toDelta().toJson();
  prefs.setString('quill_content', deltaJson);

// 从 SharedPreferences 加载
  final savedJson = prefs.getString('quill_content');
  if (savedJson != null) {
  _controller.document = quill.Document.fromJson(savedJson);
  }*/

}